// main.js
import React, { useState, useEffect } from 'react'
import {
  MenuFoldOutlined, MenuUnfoldOutlined, createFromIconfontCN, UserOutlined, FormOutlined, LogoutOutlined
} from '@ant-design/icons'
import { Button, Menu, Tabs, Modal, FloatButton, Dropdown } from 'antd'
import { useHistory, useLocation } from 'react-router-dom'
import logo from '../img/shipSRM/chlogo.png'
import './mainpage.css'
import { openNotification_util } from '../components/ship/util/util.js'
import useStore from '../components/useStore.js'
import store from '../untils/store'
import { dropByCacheKey, clearCache } from 'react-router-cache-route';
import { Menu as RightMenu, Item, contextMenu } from 'react-contexify'
import 'react-contexify/dist/ReactContexify.css';
import ResetPassword from '../components/resetpassword.js' // 修正文件名大小写
import request from '../untils/request.js'

var storage = window.localStorage

const MENU_ID = 'menu-id'

const Mainpage = () => {
  const history = useHistory();
  const location = useLocation();
  const [scList] = useState([])
  const [openKeys, setOpenKeys] = useState([])
  const [menuList, setMenuList] = useState([])//真正所有有权限的菜单
  const [showMenuList, setShowMenuList] = useState([])//需要展示的菜单
  const [menuRightList, setMenuRightList] = useState([])
  const [ifxgmm, setIfxgmm] = useState(false)
  const [activetabs, setActivetabs] = useState([{
    title: '首页',
    route: '/ship/mainpage',
    key: '/ship/mainpage',
    children: null,
    closable: false
  }])

  const [nowactiveKey, setnowActiveKey] = useState('/ship/mainpage')

  //鼠标悬浮的key
  const [nowtabkey, setnowtabkey] = useState('')

  const { collapsed, setcollapsed, nowroute, setnowroute } = useStore()
  const { localUrl, user } = store()

  const IconFont = createFromIconfontCN({//使用自定义图标
    scriptUrl: localUrl + 'icon.js',
  })

  // 完全清除用户状态的函数
  const clearUserState = () => {
    // 1. 清除所有缓存的路由
    clearCache();
    
    // 2. 重置标签页状态
    setActivetabs([{
      title: '首页',
      route: '/ship/mainpage',
      key: '/ship/mainpage',
      children: null,
      closable: false
    }]);
    
    // 3. 重置路由状态
    setnowroute({ route: '/ship/mainpage', title: '首页' });
    setnowActiveKey('/ship/mainpage');
    
    // 4. 重置菜单相关状态
    setOpenKeys([]);
    setMenuList([]);
    setShowMenuList([]);
    setMenuRightList([]);
  };

  const handleContextMenu = (event) => {
    event.preventDefault();
    contextMenu.show({
      id: MENU_ID,
      event: event,
    })
  }

  const handleCloseAll = () => {
    //设置activetabs为第一个
    setActivetabs([activetabs[0]])
    setnowroute({ route: '/ship/mainpage', title: '首页' })
    tonormal('/ship/mainpage')
    for (let i = 1; i < activetabs.length; i++) {
      dropByCacheKey(activetabs[i].key)
    }
  }

  const handleCloseOther = () => {
    setActivetabs([...activetabs.filter(tab => tab.key === nowtabkey || tab.key === '/ship/mainpage')])
    for (let i = 0; i < activetabs.length; i++) {
      if (activetabs[i].key !== nowtabkey && activetabs[i].key !== '/ship/mainpage') {
        dropByCacheKey(activetabs[i].key)
      }
    }
    setnowActiveKey(nowtabkey)
    tonormal(nowtabkey)
  }

  const handleCloseRight = () => {
    let index = activetabs.findIndex(tab => tab.key === nowtabkey)
    setActivetabs([...activetabs.slice(0, index + 1)])
    for (let i = index + 1; i < activetabs.length; i++) {
      dropByCacheKey(activetabs[i].key)
    }
    setnowActiveKey(nowtabkey)
    tonormal(nowtabkey)
  }

  const queryMenuList = async () => {//查询菜单
    // 确保用户已登录
    if (!user?.token) return;
    
    let rtdata = await request("/admin/menu/selectMenuById", {
      method: "POST",
      mode: 'cors',
    })
    for (var i = 0; i < rtdata.length; i++) {
      if (rtdata[i].icon) {//图标不为空
        rtdata[i] = {
          ...rtdata[i],
          icon: <IconFont type={rtdata[i].icon} />
        }
      }
    }
    // 1. 自定义深拷贝函数（专门处理包含 React 元素的对象）
    const deepCopy = (obj) => {
      if (typeof obj !== 'object' || obj === null) {
        return obj; // 基本类型直接返回
      }
      if (Array.isArray(obj)) {
        return obj.map(item => deepCopy(item)); // 数组递归拷贝每个元素
      }
      // 对象：复制属性，React 元素直接保留引用
      const newObj = { ...obj };
      // 如果有 children，递归拷贝
      if (newObj.children) {
        newObj.children = deepCopy(newObj.children);
      }
      return newObj;
    };
    // 2. 拷贝并过滤数据（只保留 is_show !== 0 的项）
    const show = deepCopy(rtdata).filter(item => {
      // 过滤当前层
      if (item.is_show === 0) return false;
      // 过滤 children（如果有）
      if (item.children && item.children.length > 0) {
        item.children = item.children.filter(child => child.is_show !== 0);
      }
      return true;
    });
    // 设置显示的菜单列表
    setShowMenuList(show);
    setMenuList(rtdata)
    setMenuRightList([])
  }

  // 初始化和用户切换时的处理
  useEffect(() => {
    // 当用户ID变化时重新初始化
    if (user?.id) {
      clearUserState();
      queryMenuList();
      
      // 确保路由正确
      if (location.pathname === '/' || !location.pathname.includes('/ship/')) {
        history.push('/ship/mainpage');
      }
    } else if (!user?.id && location.pathname !== '/') {
      // 如果没有用户信息且不在登录页，跳转到登录页
      history.push('/');
    }
  }, [user?.id]); // 监听user.id变化

  useEffect(() => {
    if (!user?.id) return;
    
    if (location.pathname.includes('Form') || menuList.length === 0) return;
    
    if (location.pathname !== '/ship/mainpage') {
      let flag = false
      for (let item of menuList) {
        if (item.path === location.pathname) {
          flag = true;
          break;
        }
        if (item.children) {
          for (let item2 of item.children) {
            if (item2.path === location.pathname) {
              flag = true;
              break;
            }
          }
          if (flag) break;
        }
      }
      //设置为404
      if (!flag) {
        history.push('/ship/404');
      }
    }
  }, [location, menuList, user?.id])

  const tonormal = (route) => {
    history.push(route)
  }

  useEffect(() => {
    if (!nowroute || !user?.id) return;
    
    let newActivetabs = [...activetabs];
    
    // 从完整路由中自动提取 baseRoute
    const baseRoute = nowroute.route?.split('?')[0] || '';
    
    // 动态页面判断（仅针对带查询参数的路由）
    if (nowroute.route?.includes('?')) {
      // 查找同类标签（基础路由相同的标签）
      const existingDynamicTab = activetabs.find(
        tab => tab.baseRoute === baseRoute
      );

      if (existingDynamicTab) {
        // 情况1：同类但不同ID（标题不同）→ 关闭旧标签，打开新标签
        if (existingDynamicTab.title !== nowroute.title) {
          // 过滤掉旧的同类标签
          newActivetabs = newActivetabs.filter(
            tab => tab.baseRoute !== baseRoute
          );
          
          // 添加新标签（存储基础路由）
          const newTab = {
            key: nowroute.route, // 用完整路由作为key（确保唯一）
            title: nowroute.title,
            route: nowroute.route,
            closable: true,
            baseRoute: baseRoute // 存储提取的基础路由
          };
          newActivetabs.push(newTab);
          
          // 更新状态
          setActivetabs(newActivetabs);
          setnowActiveKey(nowroute.route);
          history.push(nowroute.route);
          return;
        } 
        // 情况2：同类且同ID（标题相同）→ 复用标签
        else {
          setnowActiveKey(existingDynamicTab.key);
          history.push(nowroute.route);
          return;
        }
      } 
      // 无同类标签 → 直接添加新标签
      else {
        const newTab = {
          key: nowroute.route,
          title: nowroute.title,
          route: nowroute.route,
          closable: true,
          baseRoute: baseRoute // 存储提取的基础路由
        };
        newActivetabs.push(newTab);
        setActivetabs(newActivetabs);
        setnowActiveKey(nowroute.route);
        history.push(nowroute.route);
        return;
      }
    }

    // 非动态页面（沿用原有逻辑）
    const existingTab = activetabs.find(tab => tab.route === nowroute.route);
    if (existingTab) {
      if (existingTab.title !== nowroute.title && nowroute.title) {
        openNotification_util(`请先关闭已打开的“${existingTab.title}”页面`);
        setnowActiveKey(existingTab.key);
        return;
      } else {
        setnowActiveKey(existingTab.key);
        history.push(nowroute.route);
      }
    } else {
      const menuItem = menuRightList.find(menu => menu.cdly === nowroute.route) || {
        cdly: nowroute.route,
        cdmc: nowroute.title
      };
      const newTab = {
        key: menuItem.cdly,
        title: menuItem.cdmc,
        route: menuItem.cdly,
        closable: true
      };
      newActivetabs.push(newTab);
      setnowActiveKey(menuItem.cdly);
      history.push(nowroute.route);
      setActivetabs(newActivetabs);
    }
  }, [nowroute, user?.id]);

  const handleOpenChange = (openKeys) => {
    setOpenKeys(openKeys)
  }

  const handlelogout = () => {//退出登录
    // 1. 清除所有用户状态
    clearUserState();
    
    // 2. 清除存储
    storage.clear();
    
    // 3. 跳转到登录页并强制刷新
    history.push('/');
    window.location.reload();
  }

  const toggleCollapsed = () => {
    setcollapsed(!collapsed)
  }

  const changeSelect = (item) => {
    // 验证用户是否已登录
    if (!user?.id) {
      history.push('/');
      return;
    }
    
    let title = item.key.split("&")[0]
    let route = item.key.split("&")[1]
    // 检查key是否已存在
    const exists = activetabs.some(tab => tab.key === route);
    if (!exists) {//页面未打开时，添加到tabs
      setActivetabs([...activetabs, {
        title: title,
        route: route,
        key: route,
        closable: true
      }])
      setnowroute({ route: route, title: title })
    }
    setnowActiveKey(route)//activeKey设置为route
    tonormal(route)
  }

  var scLength = 0
  if (scList.length > 0) {
    if (scList[0].children) {
      if (scList[0].children.length > 24) {
        scLength = 24
      } else scLength = scList[0].children.length
    }
  }
  var bcnum = 24 - scLength
  var renderarr = []
  for (var i = 0; i <= bcnum; i++) {
    renderarr.push(
      <div style={{ width: "9%", height: '5vh', fontSize: '0.7rem', borderRadius: '10px', margin: "0 1vw" }}></div>
    )
  }

  return (
    <div style={{ height: '100vh', width: '100%' }}>
      <div
        style={{
          height: "100vh", width: "100%", position: 'relative', textAlign: "center", fontSize: "0.75rem", fontFamily: "Microsoft YaHei",
          backgroundSize: "100% ", backgroundRepeat: "no-repeat", backgroundColor: "#F1F1F1", overflow: "hidden",
        }}>
        <div style={{
          position: "absolute", left: "0", top: "6vh", width: collapsed ? "3%" : "15%", height: "94vh", backgroundColor: "white", overflowY: "scroll",
          overflowX: "hidden"
        }}>
          <Menu
            defaultSelectedKeys={['/ship/mainpage']}
            openKeys={openKeys}
            mode="inline"
            onOpenChange={handleOpenChange}
            onClick={changeSelect}
            items={showMenuList}
            inlineCollapsed={collapsed}
            style={{ width: '100%' }}
          />
        </div>
        <div style={{
          backgroundImage: "linear-gradient(to bottom,#e4e9eb , #F9F8F9)"
          , textAlign: "center", color: "#1f5aa9", fontSize: "0.9rem", lineHeight: "6vh",
          position: "fixed", width: "100%", height: "6vh", top: "0", fontWeight: "800", zIndex: "10"
          , borderBottom: "3px solid #fcfcfe"
        }}   >
          <img src={logo} style={{ height: '7vh', width: "7%", position: 'absolute', left: '1%', top: '0.1vh' }} />
          <Button type="primary" onClick={toggleCollapsed} style={{
            backgroundColor: collapsed ? "#1f5aa9" : "white",
            position: 'absolute', left: '12%', width: '3%', zIndex: '1', marginTop: '1vh'
          }}>
            {collapsed ? <MenuUnfoldOutlined style={{ color: "white" }} /> : <MenuFoldOutlined style={{ color: "#1f5aa9" }} />}
          </Button>
          <div style={{ 
            textAlign: "center", 
            padding: "0", 
            borderRadius: "0 0 10px 10px", 
            width: "12vw",
            height: "2vw", 
            position: "absolute", 
            fontSize: "0.6rem", 
            right: "16.5vw", 
            zIndex: '10',
            marginTop: '0vh', 
            display: "flex", 
            alignItems: "center",
            justifyContent: "center",
          }}>
            <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="info" onClick={() => { setnowroute({ route: '/ship/myselfForm', title: '我的' }) }}>
                  <Button type="link">
                    <UserOutlined />个人信息
                  </Button>
                </Menu.Item>
                <Menu.Item key="password" onClick={() => { setIfxgmm(true) }}>
                  <Button type="link">
                    <FormOutlined /> 修改密码
                  </Button>
                </Menu.Item>
                <Menu.Item key="logout" onClick={() => { handlelogout() }}>
                  <Button type="link" >
                    <LogoutOutlined />退出登录
                  </Button>
                </Menu.Item>
              </Menu>
            }
            trigger={['hover']} // 鼠标悬浮触发
          >
            <FloatButton 
              style={{ 
                color: "black", 
                position: "fixed",
                top: "0.5vh",
                right: "2vh",
                width: "12vw",
                maxHeight: "2rem",
                display: "inline-block",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap"
              }}
              description={user?.name || '未登录'}
              shape="square"
              icon={<UserOutlined />}
            />
          </Dropdown>
          </div>
        </div>
        <Modal open={ifxgmm} style={{ top: "5vh" }} onCancel={() => { setIfxgmm(false) }}
          width="20vw"
          okButtonProps={{ style: { display: "none" } }} cancelButtonProps={{ style: { display: "none" } }}
          destroyOnClose={true}
        >
          <ResetPassword hiddenbutton={true} transfer={true}
            onCancel={() => { setIfxgmm(false) }}
            setIfxgmm={e => { setIfxgmm(e) }}
          />
        </Modal>
        {/*放置一个固定的tabs栏 用于导航 高度 10vh*/}
        <Tabs
          style={{
            position: "fixed", top: "1.9vh", width: "70vw", height: "4vh", zIndex: "10", left: "16%",
            borderRadius: "10px 10px 0 0", overflow: "hidden"
          }}
          activeKey={nowactiveKey}
          onChange={(activeKey) => {
            setnowActiveKey(activeKey)
            let title = activetabs.find(tab => tab.key === activeKey)?.title
            let route = activetabs.find(tab => tab.key === activeKey)?.route
            if (title && route) {
              setnowroute({ route: route, title: title })
            }
          }}
          items={[
            ...activetabs.map(tab => ({
              label: (
                <div onMouseEnter={(e) => (setnowtabkey(tab.key))}
                onContextMenu={handleContextMenu}
                >
                  {tab.title}
                </div>
              ),
              key: tab.key,
              children: null,
              closable: tab.title == '首页' ? false : true
            }))
          ]}
          onEdit={(targetKey, action) => {
            setOpenKeys([])
            //如果列表长度等于1跳首页
            if (activetabs.length == 2) {
              let cacheKey = targetKey.split('/').pop();
              dropByCacheKey(cacheKey)
              setActivetabs([...activetabs.filter(tab => tab.key !== targetKey)]);
              setnowroute({ route: '/ship/mainpage', title: '首页' })
              tonormal('/ship/mainpage')
              return
            }
            if (action === 'remove') {
              const cacheKey = targetKey.split('/').pop();
              dropByCacheKey(cacheKey);
              // 过滤后的新标签列表（删除了targetKey对应的标签）
              const newTabs = activetabs.filter(tab => tab.key !== targetKey);
              setActivetabs(newTabs);

              // 关键逻辑：确定新的激活态
              // 1. 检查当前激活的标签（nowactiveKey）是否还在新列表中
              const currentActiveKeyStillExists = newTabs.some(tab => tab.key === nowactiveKey);
              if (currentActiveKeyStillExists) {
                // 2. 如果当前激活的标签未被删除，保持其激活态
                setnowActiveKey(nowactiveKey);
                tonormal(nowactiveKey);
              } else {
                // 3. 如果当前激活的标签被删除了，切换到新列表的最后一个标签
                const lastKey = newTabs[newTabs.length - 1].key;
                setnowActiveKey(lastKey);
                tonormal(lastKey);
              }
            }
          }}
          type="editable-card"
          hideAdd={true}
        />
      </div>
      <RightMenu id={MENU_ID} style={{zIndex: 1052}}>
        <Item onClick={handleCloseAll}>关闭全部</Item>
        <Item onClick={handleCloseOther}>关闭其他</Item>
        <Item onClick={handleCloseRight}>关闭右侧</Item>
      </RightMenu>
    </div>
  );
}

export default Mainpage
